package com.reggie.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.dto.DishDto;
import com.reggie.entity.Dish;
import com.reggie.entity.DishFlavor;
import com.reggie.service.CategoryService;
import com.reggie.service.DishFlavorService;
import com.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理(Dish)表控制层
 *
 * @author makejava
 * @since 2022-09-01 18:39:15
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    /**
     * 服务对象
     */
    @Resource
    private DishService dishService;

    @Resource
    private DishFlavorService dishFlavorService;

    @Resource
    private CategoryService categoryService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto 菜品dto
     * @return 是否成功
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        // 插入菜品的同时，增加口味数据
        dishService.saveWithFlavors(dishDto);
        // 清理对应的菜品缓存
        Set<String> keys = redisTemplate.keys("dish:" + dishDto.getCategoryId() + "_1");
        assert keys != null;
        redisTemplate.delete(keys);
        return R.success("新增成功");
    }


    /**
     * 菜品信息分页
     *
     * @param currPage 当前页码
     * @param pageSize 页面数据量
     * @param name     查询关键字
     * @return 目标查询页面
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(@RequestParam("page") int currPage, @RequestParam("pageSize") int pageSize, @RequestParam(name = "name", required = false) String name) {
        // 构造分页对象
        Page<Dish> pageInfo = new Page<>(currPage, pageSize);
        // 查询条件
        LambdaQueryWrapper<Dish> queryWrapper = Wrappers.lambdaQuery(Dish.class);
        // 查询关键字
        queryWrapper.like(StrUtil.isNotBlank(name), Dish::getName, name)
                .eq(Dish::getIsDeleted, 0)
                .orderByAsc(Dish::getCategoryId)
                .orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, queryWrapper);
        // 对象属性拷贝以满足视图需求
        Page<DishDto> realPageInfo = new Page<>();
        BeanUtil.copyProperties(pageInfo, realPageInfo, "records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> realList = records.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtil.copyProperties(dish, dishDto);
            Long categoryId = dish.getCategoryId();
            if (ObjectUtil.isNotNull(categoryId)) {
                String categoryName = categoryService.getById(categoryId).getName();
                dishDto.setCategoryName(categoryName);
            } else {
                dishDto.setCategoryName("未分类");
            }
            return dishDto;
        }).collect(Collectors.toList());
        realPageInfo.setRecords(realList);
        return R.success(realPageInfo);
    }

    /**
     * 根据id查询菜品和菜品口味
     *
     * @param id 菜品id
     * @return 菜品信息
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable("id") Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto 菜品dto
     * @return 是否成功
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        // 插入菜品的同时，增加口味数据
        dishService.updateWithFlavor(dishDto);
        // 清理所有菜品的缓存数据
        // Set<String> keys = redisTemplate.keys("dish:*");
        // redisTemplate.delete(keys);

        // 清理对应的菜品缓存
        Set<String> keys = redisTemplate.keys("dish:" + dishDto.getCategoryId() + "_1");
        assert keys != null;
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }

    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") int status, Long... ids) {
        log.info("修改目标：{}", status == 0 ? "停售" : "起售");
        dishService.updateBatchById(dishService.listByIds(Arrays.asList(ids))
                .stream()
                .peek(dish -> dish.setStatus(status))
                .collect(Collectors.toList()));
        String message = (status == 0 ? "停售成功" : "起售成功");
        return R.success(message);
    }

    @DeleteMapping
    public R delete(@RequestParam("ids") Long... ids) {
        dishService.removeByIds(Arrays.asList(ids));
        return R.success(null);
    }

    /**
     * 根据条件查询对应的菜品数据
     *
     * @param dish 查询条件
     * @return 菜品列表
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;
        ListOperations<String, String> listOperations = redisTemplate.opsForList();
        String key = "dish:" + dish.getCategoryId() + "_" + dish.getStatus();
        // 从redis中查询对应的缓存胡数据
        dishDtoList = Objects.requireNonNull(
                        listOperations
                                .getOperations()
                                .boundListOps(key)
                                .range(0, -1)
                )
                .stream()
                .map(jsonStr -> {
                    return (DishDto) JSONUtil.toBean(jsonStr, DishDto.class, false);
                })
                .collect(Collectors.toList());
        // 如果存在，直接返回，无需查询数据库
        if (ObjectUtil.isNotEmpty(dishDtoList)) {
            return R.success(dishDtoList);
        }
        // 不存在再查询数据库，更新缓存
        LambdaQueryWrapper<Dish> queryWrapper = Wrappers.lambdaQuery(Dish.class);
        queryWrapper.eq(StrUtil.isNotBlank(dish.getCategoryId().toString()), Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish::getStatus, 1)
                .orderByAsc(Dish::getSort)
                .orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(queryWrapper);
        if (ObjectUtil.isEmpty(dishList)) {
            return R.error("相关菜品未上架");
        }
        dishDtoList = dishList.stream().map(dishItem -> {
            DishDto dishDto = new DishDto();
            BeanUtil.copyProperties(dishItem, dishDto);
            LambdaQueryWrapper<DishFlavor> flavorQueryWrapper = Wrappers.lambdaQuery(DishFlavor.class);
            flavorQueryWrapper.eq(DishFlavor::getDishId, dishItem.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(flavorQueryWrapper);
            dishDto.setFlavors(flavorList);
            return dishDto;
        }).collect(Collectors.toList());
        // 写入缓存
        listOperations.rightPushAll(key, dishDtoList
                .stream()
                .map(JSONUtil::toJsonStr)
                .collect(Collectors.toList())
        );
        // 设置过期时间
        redisTemplate.expire(key, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}

